/**
 * 非开发环境下的服务端启动入口文件
 **/
const express = require('express')
const app = express()
const { createBundleRenderer } = require('vue-server-renderer')
const path = require("path")
const getContext = require('./utils/getContext')
const compression = require('compression')


const template = require('fs').readFileSync(path.resolve(__dirname, '../dist/template.ssr.html'), 'utf-8')
const serverBundle = require(path.resolve(__dirname, '../dist/vue-ssr-server-bundle.json'))
const clientManifest = require(path.resolve(__dirname, '../dist/vue-ssr-client-manifest.json'))

const renderer = createBundleRenderer(serverBundle, {
  template,
  clientManifest
})

app.use(compression()) //使用gzip文件

//引入静态文件  否则运行报错
app.use('/static', express.static(path.resolve(__dirname, '../dist')))


app.get('*', (req, res) => {
  // let token
  // try {
  //   token = req.headers.cookie.split("token=")[1].split(';')[0]
  // } catch(e) {}
  const context = getContext(req)
  context.url = req.url
  // context.token = token
  renderer.renderToString(context, (err, html) => {
    if (err) {
      console.error(err)
      if (err.code === 404) {
        res.status(404).end('Page not found')
      } else {
        res.status(500).end('Internal Server Error')
      }
    } else {
      res.status(200).end(html)
    }
  })
})

let port = 8020
app.listen(port, () => {
  console.log(`已监听 localhost:${port}`)
})